#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>

void Usage(char *args)
{
    std::cout << "Usage : " << args << " server_ip server_port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    // 1. 创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "sock failed : " << errno << std::endl;
        return 2;
    }

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);

    // 2. 连接服务器
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        std::cerr << "connect failed!" << std::endl;
        return 3;
    }
    std::cout << "connecting succeed!" << std::endl;

    // 3. 发送请求
    // while (true)
    // {
    std::cout << "Please Enter# ";
#define NUM 1024
    char buf[NUM] = {0};

    fgets(buf, NUM - 1, stdin);
    write(sock, buf, strlen(buf));

    ssize_t sz = read(sock, buf, NUM - 1);
    if (sz > 0)
    {
        buf[sz] = 0;
        std::cout << buf << std::endl;
        std::cout << "服务已结束" << std::endl;
    }
    // }
    close(sock);
}